#include <iostream>
#include <queue>
#include <pthread.h>
#include "Mutex.hpp"
#include "Cond.hpp"
using namespace std;

static int defaultnum = 10;

template <typename T>
class Blockqueue
{
private:
    bool _isfull()
    {
        return _q.size() >= defaultnum;
    }
    bool _isempty()
    {
        return _q.empty();
    }

public:
    Blockqueue(int cap = defaultnum)
        : _s_sleep(0), _p_sleep(0), _cap(cap)
    {
    }
    void Enqueue(const T &in)
    {
        {
            LockGuard lockguard(_mutex);
            while (_isfull())
            {
                _p_sleep++;
                cout << "生产队列已满" << endl;
                _full_cond.Wait(_mutex);
                _p_sleep--;
            }

            _q.push(in);
            if (_s_sleep > 0)
            {
                _empty_cond.Signal();
                cout << "唤醒消费者" << endl;
            }
        }
    }
    T Pop()
    {
        T data;
        {
            LockGuard lockguard(_mutex);
            while (_isempty())
            {
                _s_sleep++;
                cout << "消费队列为空" << endl;
                _empty_cond.Wait(_mutex);
                _s_sleep--;
            }
            data = _q.front();
            _q.pop();
            if (_p_sleep > 0)
            {
                _full_cond.Signal();
                cout << "唤醒生产者" << endl;
            }
        }
        return data;
    }
    ~Blockqueue()
    {
    }

private:
    queue<T> _q; // 存放
    int _cap;    // 容量

    int _s_sleep; // 消费者休眠数
    int _p_sleep; // 生产者休眠数

    Mutex _mutex;
    Cond _full_cond;  // 队列满条件
    Cond _empty_cond; // 队列空条件
};